package com.hqyj.springCloudTest.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.entity.common.ResultEntity;
import com.hqyj.entity.common.SearchBean;
import com.hqyj.entity.test.City;
import com.hqyj.springCloudTest.dao.CityDao;
import com.hqyj.springCloudTest.service.CityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class CityServiceImpl implements CityService {

    private final static Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);
    @Value("${server.port}")
    private int port;
    @Autowired
    private CityDao cityDao;

    @Override
    @Transactional
    public ResultEntity<City> insertCity(City city) {
        cityDao.insertCity(city);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status,"添加成功！",city);
    }

    @Override
    public ResultEntity<City> updateCity(City city) {
        cityDao.updateCity(city);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status,"修改成功！",city);
    }

    @Override
    public ResultEntity<Object> deleteCity(int cityId) {
        cityDao.deleteCity(cityId);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status,"删除成功！",cityId);
    }

    @Override
    public City getCityByCityId(int cityId) {
        LOGGER.debug(String.format("=====server port :%d ====",port));
        return cityDao.getCityByCityId(cityId);
    }

    @Override
    public List<City> getCityByCountryId(int countryId) {
        return cityDao.getCityByCountryId(countryId);
    }

    @Override
    public PageInfo<City> getCityBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<City>(
                //判断是否为空
                Optional.ofNullable(cityDao.getCityBySearchBean(searchBean))
                        //如果是空就返回一个空的集合
                        .orElse(Collections.emptyList()));
    }
}
